package com.mingtu.guards.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.ResultCallback;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.liteav2.basic.UserModel;
import com.mingtu.guards.bean.TIMOnlineBean;
import com.mingtu.guards.callback.MyStringDialogCallback;
import com.mingtu.offlineliteav.trtccalling.TUICalling;
import com.mingtu.offlineliteav.trtccalling.TUICallingImpl;
import com.mingtu.offlineliteav.trtccalling.model.impl.base.CallingInfoManager;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.ContactsPeopleAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.ContactsPeopleBean;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.ADMIN;
import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class ContactsPeopleListActivity extends MyBaseActivity {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;

    private String deptId;
    private ContactsPeopleAdapter contactsPeopleAdapter;
    private BasePopupView popupView;
    private boolean mIsKickedOffline = false;
    private boolean mIsUserSigExpired = false;
    private TUICalling.Type mType; //表示当前是 videocall/audiocall
    private UserModel mSearchModel;
    private String mobile;
    private BasePopupView tipPopupView;
    private String receiveUserName;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_contacts_people_list;
    }

    @Override
    protected void initView() {
        setModuleTitle("");
        super.initView();
    }

    @Override
    protected void initData() {
        deptId = getIntent().getStringExtra("deptId");
        String deptName = getIntent().getStringExtra("deptName");

        if (!StringUtils.isEmpty(deptName)) {
            setModuleTitle(deptName);
        }


        mIsKickedOffline = SPStaticUtils.getBoolean(MySPTools.mIsKickedOffline);
        mIsUserSigExpired = SPStaticUtils.getBoolean(MySPTools.mIsUserSigExpired);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recycler.setLayoutManager(linearLayoutManager);
//        recycler.addItemDecoration(new CustomDecoration(context, CustomDecoration.VERTICAL_LIST, R.drawable.shape_dive_line, 0));
        recycler.addItemDecoration(new TopSpaceItemDecoration());
        recycler.addItemDecoration(new BottomSpaceItemDecoration());

        contactsPeopleAdapter = new ContactsPeopleAdapter();
        if (isOpenLoadAnimation) {
            contactsPeopleAdapter.isFirstOnly(isFirstOnly);
            contactsPeopleAdapter.openLoadAnimation(animationType);
        }
        contactsPeopleAdapter.setEmptyView(new EmptyDataLayout(context));
        recycler.setAdapter(contactsPeopleAdapter);
        contactsPeopleAdapter.setOnItemChildClickListener(new MyOnItemClickListener());
    }

    @Override
    protected void getData() {
        getDeptPeople();
        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupView != null) {
            popupView.destroy();
        }
        if (tipPopupView != null) {
            tipPopupView.destroy();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(context, Permission.CALL_PHONE)) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + mobile);
                intent.setData(data);
                startActivity(intent);
            } else {
                ToastUtils.showLong("拨打电话权限获取失败");
            }
        }


    }

    private void initListener() {
        initPullRefresh();//刷新
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setEnableLoadMore(false);
        srlUp.setEnableOverScrollDrag(true);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                getDeptPeople();
            }
        });
    }

    /**
     * 获取部门下的人员
     */
    private void getDeptPeople() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deptId", deptId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.GET_CONTACTS_DEPT_PERSON)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ContactsPeopleBean contactsPeopleBean = new ContactsPeopleBean();
                                contactsPeopleBean = gson.fromJson(result, ContactsPeopleBean.class);
                                List<ContactsPeopleBean.ListBean> dataBeans = contactsPeopleBean.getList();

                                try {
                                    if (dataBeans != null && dataBeans.size() > 0) {
                                        //请求时先清空数组，防止下拉操作的时候加载重复数据
                                        contactsPeopleAdapter.getData().clear();
                                        contactsPeopleAdapter.addData(dataBeans);

                                    } else {
                                        ToastUtils.showLong("抱歉，该机构下暂时没有工作人员哦~");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {

                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }

                        }
                    }
                });

    }

    /**
     * 底部弹出的pop
     */
    public class BottomPopup extends BottomPopupView implements View.OnClickListener {

        public BottomPopup(@NonNull Context context) {
            super(context);

        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.liteav_bottom_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            TextView tvAudioType = (TextView) findViewById(R.id.tv_audio_type);
            TextView tvVideoType = (TextView) findViewById(R.id.tv_video_type);
            TextView tvCancelCall = (TextView) findViewById(R.id.tv_cancel_call);
            tvAudioType.setOnClickListener(this);
            tvVideoType.setOnClickListener(this);
            tvCancelCall.setOnClickListener(this);

        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_audio_type:
                    popupView.dismiss();
                    if (!checkUserStatus()) {
                        return;
                    }
                    mType = TUICalling.Type.AUDIO;
                    startCallSomeone();
                    break;
                case R.id.tv_video_type:
                    popupView.dismiss();
                    if (!checkUserStatus()) {
                        return;
                    }
                    mType = TUICalling.Type.VIDEO;
                    startCallSomeone();
                    break;
                case R.id.tv_cancel_call:
                    popupView.dismiss();
                    break;
            }
        }
    }

    private boolean checkUserStatus() {
        if (mIsKickedOffline) {
            ToastUtils.showShort(getString(R.string.trtccalling_user_kicked_offline));
        }
        if (mIsUserSigExpired) {
            ToastUtils.showShort(getString(R.string.trtccalling_user_sig_expired));
        }
        return !mIsKickedOffline && !mIsUserSigExpired;
    }

    /**
     * 开始呼叫某人
     */
    private void startCallSomeone() {
//        if (mType == TRTCCalling.TYPE_VIDEO_CALL) {
//            ToastUtils.showShort(getString(R.string.toast_video_call, mSearchModel.userName));
//            String[] userIDs = {mSearchModel.userId};
//            Bundle bundle = new Bundle();
//            bundle.putString(TUICallingConstants.PARAM_NAME_TYPE, TUICallingConstants.TYPE_VIDEO);
//            bundle.putStringArray(TUICallingConstants.PARAM_NAME_USERIDS, userIDs);
//            bundle.putString(TUICallingConstants.PARAM_NAME_GROUPID, "");
////            TUICore.callService(TUIConstants.Service.TUI_CALLING, TUICallingConstants.METHOD_NAME_CALL, bundle);
//            TUICallingManager.sharedInstance().call(userIDs, TUICalling.Type.VIDEO);
//        } else if (mType == TRTCCalling.TYPE_AUDIO_CALL) {
//            ToastUtils.showShort(getString(R.string.toast_voice_call, mSearchModel.userName));
//            String[] userIDs = {mSearchModel.userId};
//            Bundle bundle = new Bundle();
//            bundle.putString(TUICallingConstants.PARAM_NAME_TYPE, TUICallingConstants.TYPE_AUDIO);
//            bundle.putStringArray(TUICallingConstants.PARAM_NAME_USERIDS, userIDs);
//            bundle.putString(TUICallingConstants.PARAM_NAME_GROUPID, "");
////            TUICore.callService(TUIConstants.Service.TUI_CALLING, TUICallingConstants.METHOD_NAME_CALL, bundle);
//            TUICallingManager.sharedInstance().call(userIDs, TUICalling.Type.AUDIO);
//        }

        String[] userIDs = {mSearchModel.userId};
        TUICallingImpl.sharedInstance(this).call(userIDs, mType);
        getAdminUserSign(mSearchModel.userId);

    }

    /**
     * 音视频呼叫
     *
     * @param userId
     */
    private void callAvEvent(String userId) {
        CallingInfoManager.getInstance().getUserInfoByUserId(userId, new CallingInfoManager.UserCallback() {
            @Override
            public void onSuccess(com.mingtu.offlineliteav.trtccalling.model.impl.UserModel model) {
                mSearchModel = new UserModel();
                mSearchModel.userId = model.userId;
                mSearchModel.userName = TextUtils.isEmpty(model.userName) ? model.userId : model.userName;

                popupView = new XPopup.Builder(ContactsPeopleListActivity.this)
                        .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                        .enableDrag(true)
                        .isDarkTheme(true)
                        .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(new BottomPopup(ContactsPeopleListActivity.this))
                        .show();
                KeyboardUtils.hideSoftInput(ContactsPeopleListActivity.this);
            }

            @Override
            public void onFailed(int code, String msg) {
                MyLogUtil.e("testtest", "code ==" + code + ",msg==" + msg);
                if (code == -1) {
                    tipPop("对方暂无联系方式，不能进行音视频通话哦！");
                } else if (code == 6013) {
                    tipPop("您的账号没有联系电话，不能进行音视频通话哦！");
                } else if (code == 70107) {
                    tipPop("对方还未拥有视音频通话功能，不能进行音视频通话哦！");
                } else {
                    ToastUtils.showLong(getString(R.string.trtccalling_toast_call_fail, msg));
                }
            }
        });

    }

    /**
     * 提示的XPopup
     *
     * @param content
     */
    private void tipPop(String content) {
        tipPopupView = new XPopup.Builder(ContactsPeopleListActivity.this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .hasShadowBg(true)
                .asConfirm(context.getResources().getString(R.string.text_tip),
                        content,
                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                        null, null,
                        true);
        tipPopupView.show();
    }

    /**
     * 列表的点击事件
     */
    private class MyOnItemClickListener implements BaseQuickAdapter.OnItemChildClickListener {

        @Override
        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
            ContactsPeopleBean.ListBean bean = contactsPeopleAdapter.getData().get(position);
            mobile = bean.getMobile();
            receiveUserName = bean.getUsername();
            if (StringUtils.isEmpty(mobile)) {
                tipPop("抱歉,对方暂无联系电话！");
                return;
            }
            switch (view.getId()) {
                case R.id.iv_call:
                    XXPermissions.with(ContactsPeopleListActivity.this)
                            .permission(Permission.CALL_PHONE)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (permissions.contains(Permission.CALL_PHONE)) {

//                                            Intent intent = new Intent(Intent.ACTION_CALL);
//                                            Uri data = Uri.parse("tel:" + mobile);
//                                            intent.setData(data);
//                                            startActivity(intent);

                                        Intent intent = new Intent(Intent.ACTION_DIAL);
                                        Uri data = Uri.parse("tel:" + mobile);
                                        intent.setData(data);
                                        startActivity(intent);
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (never) {
                                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                        ToastUtils.showLong("请手动授予拨打电话权限");
                                        XXPermissions.startPermissionActivity(ContactsPeopleListActivity.this, permissions);
                                    } else {

                                    }

                                }
                            });


                    break;
                case R.id.iv_video:
                    callAvEvent(mobile);
                    break;
            }
        }
    }

    /**
     * 获取腾讯实时音视频管理员的userSig,这里的参数只能是administrator
     *
     * @param receiverUserId
     */
    private void getAdminUserSign(String receiverUserId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("message", ADMIN);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_USER_SIG + "/" + ADMIN)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                String sign = jsonObject.getString("sign");
                                getUserTIMOnlineStatus(receiverUserId, sign, new ResultCallback() {
                                    @Override
                                    public void result(Object object) {
                                        boolean b = Boolean.parseBoolean(object.toString());
                                        if (b) {
                                            sendJpushOfflineMessage();
                                        }else{
                                            sendJpushOnlineMessage();
                                        }
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });
    }

    /**
     * 查询帐号在线状态
     *
     * @param receiverUserId
     * @param usersig
     * @param resultCallback
     */

    private void getUserTIMOnlineStatus(String receiverUserId, String usersig, ResultCallback resultCallback) {
        String appid = SPStaticUtils.getString(MySPTools.TUI_APPID);
        List<String> accounts = new ArrayList<>();
        accounts.add(receiverUserId);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("To_Account", accounts);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.TIM_ONLINE_STATUS)
                .tag(this)
                .isSpliceUrl(true)
                .params("sdkappid", appid)
                .params("identifier", ADMIN)
                .params("usersig", usersig)
                .params("random", getRandom())
                .params("contenttype", "json")
                .upJson(str)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body(); //{"ActionStatus":"OK","ErrorInfo":"","ErrorCode":0,"QueryResult":[{"To_Account":"19839753216","Status":"PushOnline"}]}
                        try {
                            Gson gson = GsonFactory.getSingletonGson();
                            TIMOnlineBean timOnlineBean = new TIMOnlineBean();
                            timOnlineBean = gson.fromJson(result, TIMOnlineBean.class);
                            String actionStatus = timOnlineBean.getActionStatus();
                            if (actionStatus.equals("OK")) {
                                List<TIMOnlineBean.QueryResultBean> queryResultBeans = timOnlineBean.getQueryResult();
                                TIMOnlineBean.QueryResultBean queryResultBean = queryResultBeans.get(0); //因为是单条数据请求。这里只有一条数据
                                String status = queryResultBean.getStatus();
                                if (status.equals("PushOnline")) { //离线状态
                                    resultCallback.result(true);
                                } else {
                                    resultCallback.result(false);
                                }
                            }

                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    /**
     * 极光发送离线消息
     */
    private void sendJpushOfflineMessage() {
        String loginUserName = SPStaticUtils.getString(SPTools.userName);
        String alert = "";
        if (mType == TUICalling.Type.AUDIO) {
            alert = "请求语音通话";
        } else if (mType == TUICalling.Type.VIDEO) {
            alert = "请求视频通话";
        }


        HashMap<String, Object> intent = new HashMap<>();
        intent.put("url", "intent:#Intent;action=android.intent.action.MAIN;end");

        HashMap<String, Object> android = new HashMap<>();
        android.put("alert", alert);
        android.put("title", loginUserName);
        android.put("intent", intent);
        android.put("sound", "/raw/phone_ringing");//铃声,这里使用的是腾讯音视频里面的铃声
//        android.put("channel_id", "high_system");

        HashMap<String, Object> notification = new HashMap<>();
        notification.put("alert", alert);
        notification.put("android", android);


        List<String> alias = new ArrayList<>();
        alias.add(receiveUserName);

        HashMap<String, Object> audience = new HashMap<>();
        audience.put("alias", alias);

        HashMap<String, Object> huawei = new HashMap<>();
        huawei.put("importance", "HIGH");
        huawei.put("default_sound", false);
        huawei.put("sound", "/raw/phone_ringing");
        huawei.put("category", "VOIP"); //为了适配华为、vivo 手机厂商消息，用于标识消息类型，确定消息提醒方式，对特定类型消息加快发送;

        HashMap<String, Object> honor = new HashMap<>();
        honor.put("importance", "NORMAL");

        HashMap<String, Object> vivo = new HashMap<>();
        vivo.put("category", "IM"); //为了适配华为、vivo 手机厂商消息，用于标识消息类型，确定消息提醒方式，对特定类型消息加快发送;


        HashMap<String, Object> xiaomi = new HashMap<>();
        xiaomi.put("channel_id", "112267"); //当传递了 channel_id 时  sound属性不生效

        HashMap<String, Object> thirdPartyChannel = new HashMap<>();
        thirdPartyChannel.put("huawei", huawei);
        thirdPartyChannel.put("honor", honor);
        thirdPartyChannel.put("vivo", vivo);
        thirdPartyChannel.put("xiaomi", xiaomi);

        HashMap<String, Object> options = new HashMap<>();
        options.put("third_party_channel", thirdPartyChannel);
        options.put("classification", 1);


        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("platform", "android");
        hashMap.put("notification", notification); // 极光/OPPO/FCM 通道通知实现
        hashMap.put("audience", audience); //别名
        hashMap.put("options", options);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.JPUSH_SERVER)
                .tag(this)
                .upJson(str)
                .execute(new MyStringDialogCallback(ActivityUtil.getTopActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                        }
                    }
                });
    }


    /**
     * 极光发送在线消息
     */
    private void sendJpushOnlineMessage() {
        String loginUserName = SPStaticUtils.getString(SPTools.userName);
        String alert = "";
        if (mType == TUICalling.Type.AUDIO) {
            alert = "请求语音通话";
        } else if (mType == TUICalling.Type.VIDEO) {
            alert = "请求视频通话";
        }


        HashMap<String, Object> android = new HashMap<>();
        android.put("alert", alert);
        android.put("title", loginUserName);

        HashMap<String, Object> notification = new HashMap<>();
        notification.put("alert", alert);
        notification.put("android", android);


        List<String> alias = new ArrayList<>();
        alias.add(receiveUserName);

        HashMap<String, Object> audience = new HashMap<>();
        audience.put("alias", alias);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("platform", "android");
        hashMap.put("notification", notification); // 极光/OPPO/FCM 通道通知实现
        hashMap.put("audience", audience); //别名

        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.JPUSH_SERVER)
                .tag(this)
                .upJson(str)
                .execute(new MyStringDialogCallback(ActivityUtil.getTopActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                        }
                    }
                });
    }

    /**
     * 生成8位随机数
     *
     * @return
     */
    private String getRandom() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 8; i++) {
            //首字母不能为0
            result += (random.nextInt(9) + 1);
        }
        return result;
    }

}